package com.mingtu.guards.activity;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.adapter.DepartStaffAdapter;
import com.mingtu.center.adapter.LeaderDepartmentAdapter;
import com.mingtu.center.bean.DepartStaffBean;
import com.mingtu.center.bean.DeptNameBean;
import com.mingtu.common.bean.UserInfoBean;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.CalendarPickerUtils;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.viewpager.NoScrollViewPager;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.TabbarAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.fragment.ReceiveTaskFragment;
import com.mingtu.guards.fragment.SendTaskFragment;
import com.mingtu.guards.view.TimeFilterView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TaskListActivity2 extends MyBaseActivity {

    @BindView(R.id.view_pager)
    NoScrollViewPager viewPager;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.iv_send_task)
    ImageView ivSendTask;
    @BindView(R.id.tv_cancel)
    TextView tvCancel2;
    @BindView(R.id.tv_fold_depart2)
    TextView tvFoldDepart2;
    @BindView(R.id.layout_arrow_depart2)
    LinearLayout layoutArrowDepart2;
    @BindView(R.id.layout_depart)
    RelativeLayout layoutDepart;
    @BindView(R.id.recycler_depart2)
    RecyclerView recyclerDepart2;
    @BindView(R.id.tv_fold_people)
    TextView tvFoldPeople;
    @BindView(R.id.layout_arrow_people)
    LinearLayout layoutArrowPeople;
    @BindView(R.id.layout_people)
    RelativeLayout layoutPeople;
    @BindView(R.id.recycler_people)
    RecyclerView recyclerPeople;
    @BindView(R.id.radio_group_task)
    RadioGroup radioGroupTask;
    @BindView(R.id.tv_reset)
    TextView tvReset2;
    @BindView(R.id.tv_sure)
    TextView tvSure2;
    @BindView(R.id.scrollView2)
    ScrollView scrollView2;
    @BindView(R.id.layout_right_drawer)
    LinearLayout layoutRightDrawer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.status_bar_view_right_drawer)
    View statusBarViewRightDrawer;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.time_filter_time)
    TimeFilterView timeFilterTime;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private int menuPosition = 0;
    private int navPosition = 0;

    //侧滑栏
    private boolean startTimeFlag2 = false; //默认未选择开始时间
    private boolean departFlag2 = false; //记录部门是否展开
    private boolean peopleFlag = false; //记录人员是否展开
    private long startTimeMillis2;
    private long endTimeMillis2;
    private String beginTime = null;
    private String endTime = null;
    private DepartStaffAdapter departStaffAdapter;
    private LeaderDepartmentAdapter leaderDepartmentAdapter;
    private List<DeptNameBean.ListBean> departBeans2;
    private List<DeptNameBean.ListBean> myDepartBeans2;

    private List<DepartStaffBean.ListBean> departStaffBeans;
    private List<DepartStaffBean.ListBean> myDepartStaffBeans;
    private DeptNameBean deptNameBean2;
    private List<String> userIdList = null;
    private boolean isSendAuth;
    private SendTaskFragment sendTaskFragment;
    private ReceiveTaskFragment receiveTaskFragment;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_task_list2;
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(statusBarView);
        StatusBarUtil.addStatusBarHeight(statusBarViewRightDrawer);
    }

    @Override
    protected void initData() {
        receiveTaskFragment = ReceiveTaskFragment.getInstance();
        sendTaskFragment = SendTaskFragment.getInstance();
        mFragments.add(receiveTaskFragment);
        mFragments.add(sendTaskFragment);

        viewPager.setOffscreenPageLimit(2);//需要设置此值
        viewPager.setAdapter(new TabbarAdapter(getSupportFragmentManager(), mFragments));

        //主界面的Menu类型
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_but1:
                        menuPosition = 0;
                        viewPager.setCurrentItem(0, true);
                        break;
                    case R.id.rb_but2:
                        menuPosition = 1;
                        viewPager.setCurrentItem(1, true);
                        break;
                }
            }
        });

        //侧边栏的任务类型
        radioGroupTask.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_task1:

                        break;
                    case R.id.rb_task2:

                        break;
                }
            }
        });

        //部门列表
        FlexboxLayoutManager flm2 = new FlexboxLayoutManager(this);
        flm2.setFlexWrap(FlexWrap.WRAP);
        flm2.setFlexDirection(FlexDirection.ROW);
        flm2.setAlignItems(AlignItems.STRETCH);
        flm2.setJustifyContent(JustifyContent.FLEX_START);
        recyclerDepart2.setLayoutManager(flm2);

        leaderDepartmentAdapter = new LeaderDepartmentAdapter(context, null);
        recyclerDepart2.setAdapter(leaderDepartmentAdapter);
        leaderDepartmentAdapter.setOnItemClickListener(new LeaderDepartmentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                leaderDepartmentAdapter.checked(position);

                String deptId = deptNameBean2.getList().get(position).getDeptId() + "";
                getPeopleList(deptId);

                //恢复人员名称的初始值
                peopleFlag = false;
                tvFoldPeople.setText("展开");
            }
        });

        //部门人员列表
        FlexboxLayoutManager flm3 = new FlexboxLayoutManager(this);
        flm3.setFlexWrap(FlexWrap.WRAP);
        flm3.setFlexDirection(FlexDirection.ROW);
        flm3.setAlignItems(AlignItems.STRETCH);
        flm3.setJustifyContent(JustifyContent.FLEX_START);
        recyclerPeople.setLayoutManager(flm3);


        departStaffAdapter = new DepartStaffAdapter(context, null);
        recyclerPeople.setAdapter(departStaffAdapter);

        boolean isContains = SPStaticUtils.contains(SPTools.sendAuth);

        if (!isContains) {
            getUserInfo();
        } else {
            //是否有下发权限
            isSendAuth = SPStaticUtils.getBoolean(SPTools.sendAuth);
            if (isSendAuth) {
                ivSendTask.setVisibility(View.VISIBLE);
                radioGroup.setVisibility(View.VISIBLE);
            }
        }
        timeFilterTime.setOnTimeResultListener(new TimeFilterView.OnTimeResultListener() {
            @Override
            public void onResult(Date startDate, Date endDate) {
                beginTime = UIUtils.getTime3(startDate);
                endTime = UIUtils.getTime3(endDate);
            }
        });

    }

    @Override
    protected void getData() {
        getDeptList();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == 200) {
                //新增下发成功之后 返回刷新未完成列表的数据
                sendTaskFragment.refreshSendUndoTaskData();
                receiveTaskFragment.refreshReceiveUndoTaskData();
            }
        }
    }

    @OnClick({R.id.iv_send_task, R.id.tv_cancel, R.id.tv_reset, R.id.tv_sure, R.id.layout_right_drawer,
            R.id.drawer_layout, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ActivityUtil.removeActivity(this);
                break;
            case R.id.iv_send_task:
                //下发
                IntentUtils.getInstance().readyGoForResult(TaskListActivity2.this, SendTaskAddActivity.class, 100);
                break;
            case R.id.tv_cancel:
                closeDrawer();
                break;
            case R.id.tv_reset:
                closeDrawer();
                resetData();
                CalendarPickerUtils.getInstance().resetData();
                break;
            case R.id.tv_sure:
                closeDrawer();
                userIdList = departStaffAdapter.getUserIdList();
                if (userIdList.size() == 0) {
                    ToastUtils.showLong("请选择人员");
                    return;
                }
                departStaffAdapter.resetData();
                break;
            case R.id.layout_arrow_depart2:
                if (departFlag2) { //默认为false,收起状态
                    departFlag2 = false;
                    tvFoldDepart2.setText("展开");
                    leaderDepartmentAdapter.upData(myDepartBeans2);
                } else {
                    departFlag2 = true;
                    tvFoldDepart2.setText("收起");
                    leaderDepartmentAdapter.upData(departBeans2);
                }
                break;
            case R.id.layout_arrow_people:
                if (peopleFlag) { //默认为false,收起状态
                    peopleFlag = false;
                    tvFoldPeople.setText("展开");
                    departStaffAdapter.upData(myDepartStaffBeans);
                } else {
                    peopleFlag = true;
                    tvFoldPeople.setText("收起");
                    departStaffAdapter.upData(departStaffBeans);
                }
                break;
        }
    }

    private void resetData() {
        departStaffAdapter.resetData();
        beginTime = null;
        endTime = null;
        userIdList = null;
        timeFilterTime.resetData();
    }

    /**
     * 关闭侧边栏
     */
    public void closeDrawer() {
        drawerLayout.closeDrawer(layoutRightDrawer, true);
    }

    /**
     * 打开侧边栏
     */
    public void openDrawer() {
        drawerLayout.openDrawer(layoutRightDrawer);
    }

    /**
     * 获得部门名字数据
     */
    private void getDeptList() {
        OkGo.<String>post(Constant.getInstance().POST_DEPT_LIST2)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                deptNameBean2 = new DeptNameBean();
                                deptNameBean2 = gson.fromJson(result, DeptNameBean.class);

                                if (deptNameBean2 != null) {
                                    departBeans2 = deptNameBean2.getList();

                                    if (departBeans2 != null) {
                                        if (departBeans2.size() > 0) {
                                            if (departBeans2.size() > 6) {
                                                //数据大于6的时候，取前6条数据，有展开收回操作
                                                myDepartBeans2 = departBeans2.subList(0, 6);
                                                leaderDepartmentAdapter.upData(myDepartBeans2);
                                                layoutArrowDepart2.setVisibility(View.VISIBLE);

                                            } else {
                                                //数据个数小与6的时候，展开视图隐藏
                                                leaderDepartmentAdapter.upData(departBeans2);
                                                layoutArrowDepart2.setVisibility(View.GONE);
                                            }

                                            //默认加载第一个保护站的员工
                                            String defaultDeptId = deptNameBean2.getList().get(0).getDeptId() + "";
                                            getPeopleList(defaultDeptId);
                                        }
                                    }

                                }


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

    /**
     * 获得部门下面的人员数据
     */
    private void getPeopleList(String deptId) {

        OkGo.<String>get(Constant.getInstance().GET_DEPART_PEOPLE)
                .tag(this)
                .params("deptId", deptId)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                DepartStaffBean departStaffBean = new DepartStaffBean();
                                departStaffBean = gson.fromJson(result, DepartStaffBean.class);
                                departStaffBeans = departStaffBean.getList();

                                if (departStaffBeans != null) {
                                    if (departStaffBeans.size() > 0) {

                                        if (departStaffBeans.size() > 12) {
                                            myDepartStaffBeans = departStaffBeans.subList(0, 12);
                                            departStaffAdapter.upData(myDepartStaffBeans);
                                            layoutArrowPeople.setVisibility(View.VISIBLE);
                                        } else {
                                            departStaffAdapter.upData(departStaffBeans);
                                            layoutArrowPeople.setVisibility(View.GONE);
                                        }


                                    }
                                }
                            } catch (JsonSyntaxException e) {

                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }


                        }
                    }
                });
    }

    //用于兼容登录过的用户
    private void getUserInfo() {
        OkGo.<String>get(Constant.getInstance().GET_USER_INFO)
                .tag(this)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                UserInfoBean userInfoBean = new UserInfoBean();
                                userInfoBean = gson.fromJson(result, UserInfoBean.class);

                                UserInfoBean.UserBean userBean = userInfoBean.getUser();
                                List<UserInfoBean.UserBean.RoleListBean> roleList = userBean.getRoleList();

                                if (roleList.size() > 0) {
                                    UserInfoBean.UserBean.RoleListBean roleListBean = roleList.get(0);
                                    List<UserInfoBean.UserBean.RoleListBean.MenuAppListBean> menuAppListBean = roleListBean.getMenuAppList();
                                    if (menuAppListBean != null) {
                                        if (menuAppListBean.size() > 0) {
                                            List<String> typeList = new ArrayList<>();
                                            for (int i = 0; i < menuAppListBean.size(); i++) {
                                                String path = menuAppListBean.get(i).getPath(); //isLeader 1：职员 0：普通
                                                typeList.add(path);
                                            }
                                            //是否有下发权限
                                            if (typeList.contains("task")) {
                                                SPStaticUtils.put(SPTools.sendAuth, true);
                                            } else {
                                                SPStaticUtils.put(SPTools.sendAuth, false);
                                            }
                                        } else {
                                            SPStaticUtils.put(SPTools.sendAuth, false);
                                        }
                                    } else {
                                        SPStaticUtils.put(SPTools.sendAuth, false);
                                    }
                                }

                                isSendAuth = SPStaticUtils.getBoolean(SPTools.sendAuth);
                                if (isSendAuth) {
                                    ivSendTask.setVisibility(View.VISIBLE);
                                    radioGroup.setVisibility(View.VISIBLE);
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });


    }

}